package com.apes.autoparts.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.product.model.EPCVersionContrast;
import com.apes.autoparts.product.model.TyreProduct;
import com.apes.autoparts.product.repository.ProductDao;
import com.apes.autoparts.product.repository.TyreProductRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 类描述：轮胎标准商品服务类
 *
 * @ClassName TyreProductService
 * @Description 描述
 * @Author lilong
 * @Date 2022/10/26 11:26
 * @Version 1.0
 */
@Service
public class TyreProductService extends DomainService {

    @Autowired
    private TyreProductRepository tyreProductRepository;

    @Autowired
    private ProductDao productDao;


    /**
     * 动态条件查询
     * @param request
     */
    public Map conditionQuery(SimpleRequest request){
        JSONObject jo = request.getJO();

        String brand = jo.getString("brand");
        String pn = jo.getString("pn");
        String specification = jo.getString("specification");
        String figure = jo.getString("figure");
        Boolean antiExplosion = jo.getBoolean("antiExplosion");
        int page = jo.getInteger("page") < 0 || jo.getInteger("page")==null ? 0 : jo.getInteger("page");
        if (Objects.isNull(brand) && Objects.isNull(pn) && Objects.isNull(specification)) {
            Page<TyreProduct> typePage = tyreProductRepository.findAll(PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
            return MapUtil.mapper("content", typePage.getContent(), "page", page, "sum", typePage.getTotalPages());
        }
        Page<TyreProduct> typePage = tyreProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("brand", "EQ", brand,
                        "pn", "EQ", pn,
                        "specification", "EQ", specification,
                        "figure", "LIKE", figure,
                        "antiExplosion","EQ",antiExplosion),
                PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", typePage.getContent(), "page", page, "sum", typePage.getTotalPages(), "size", typePage.getTotalElements());
    }

    /**
     * 根据ERP商品id查询标准商品数据
     * @param request
     * @return
     */
    public TyreProduct findOneERPProductId(SimpleRequest request){
        return tyreProductRepository.findOneERPProductId(request.get("productId"));
    }


    /**
     * 放弃编辑回显当前数据
     * @param request
     * @return
     */
    public Map tyreProductFindOne(SimpleRequest request){
        List<TyreProduct> list = request.getA("tyreProductItems", TyreProduct.class);
        return MapUtil.mapper("tyreProductItems",list);
    }

    public List findDistinctSpecification(SimpleRequest request){
        return tyreProductRepository.findLikeModel(request.get("key"));
    }



    /**
     * 批量更新原厂标准商品
     *
     */
    public Map edit(SimpleRequest request){
        //新增和修改
        List<TyreProduct> tyreProductList = request.getA("tyreProductItems", TyreProduct.class);
        //根据id判断新增
        List<TyreProduct> newTyreProduct = tyreProductList.stream().filter(tyreProduct -> Objects.isNull(tyreProduct.getId()) || "".equals(tyreProduct.getId()))
                .collect(Collectors.toList());

        //获取删除的数据,如果没有不删除
        if (Objects.nonNull(request.getJO().get("del"))){
            List<TyreProduct> delTyreProduct = request.getA("del", TyreProduct.class);
            delTyreProduct.forEach(tyreProduct -> {
                if (Objects.nonNull(tyreProduct.getId())){
                    tyreProductRepository.delete(tyreProduct);
                }
            });
        }

        productDao.tyreProductInsert(newTyreProduct);

        return  MapUtil.mapper("tyreProductItems", newTyreProduct);

    }


    /**
     * 定制导入轮胎标准商品
     * @param request
     * @return
     */
    public JSONObject importTyreProduct(SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        String key = appendImportReturn_New(importData, titleColumnArray);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    /**
     * 并行流导入
     * @param importData
     * @param titleColumnArray
     * @return
     */
    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray) {

        AtomicReference<String> key = new AtomicReference<>();
        Set<String> stringHashSet = new HashSet<>();
        JSONArray titleArray = new JSONArray(11);
        titleArray.add("品牌");
        titleArray.add("零件名称");
        titleArray.add("规格");
        titleArray.add("花纹");
        titleArray.add("载重指数");
        titleArray.add("速度等级");
        titleArray.add("是否防爆");
        titleArray.add("产品描述");
        titleArray.add("单位");
        titleArray.add("条形码");
        titleArray.add("ERP商品编码");
        titleColumnArray.add(titleArray);

        List<TyreProduct> dataList = Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            if (((JSONArray) importDataValueArray.get(0)).size() != 11) throw new RuntimeException("导入模板错误，请检查文件并重新上传！");

            importDataValueArray.parallelStream().forEach(item -> {
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() == 0) return;

                String brand = "";
                String pn = "";
                String specification = "";
                String figure = "";
                String loadIndex = "";
                String speedClass = "";
                String antiExplosion = "";
                String describe = "";
                String unit = "";
                String barCode = "";
                String ERPProductId = "";

                for (int i = 0; i < iValueArray.size(); i++) {
                    if (Objects.isNull(iValueArray.get(i))) continue;
                    switch (i) {
                        case 0: brand = iValueArray.getString(0);
                            break;
                        case 1: pn = iValueArray.getString(1);
                            break;
                        case 2: specification = iValueArray.getString(2);
                            break;
                        case 3: figure = iValueArray.getString(3);
                            break;
                        case 4: loadIndex = iValueArray.getString(4);
                            break;
                        case 5: speedClass = iValueArray.getString(5);
                            break;
                        case 6: antiExplosion = iValueArray.getString(6);
                            break;
                        case 7: describe = iValueArray.getString(7);
                            break;
                        case 8: unit = iValueArray.getString(8);
                            break;
                        case 9: barCode = iValueArray.getString(9);
                            break;
                        case 10: ERPProductId = iValueArray.getString(10);
                            break;
                    }
                }
                //跳过首行标题行
                if ("零件名称".equals(pn) && "品牌".equals(brand)) {    // 匹配中文
                    return;
                }
               // if (!stringHashSet.add( brand + specification+figure+loadIndex+speedClass+antiExplosion)) throw new RuntimeException("导入重复数据，请重新导入！");
                TyreProduct tyreProduct = new TyreProduct();
                tyreProduct.setBrand(brand);
                tyreProduct.setPn(pn);
                tyreProduct.setSpecification(specification);
                tyreProduct.setFigure(figure);
                tyreProduct.setLoadIndex(loadIndex);
                tyreProduct.setSpeedClass(speedClass);
                tyreProduct.setAntiExplosion("是".equals(antiExplosion));
                tyreProduct.setDescribe(describe);
                tyreProduct.setUnit(unit);
                tyreProduct.setBarCode(barCode);
                tyreProduct.setERPProductId(ERPProductId);

                dataList.add(tyreProduct);
            });
        });
        productDao.tyreProductInsert(dataList);
        return key.get();
    }

    /**
     * 下载
     * @param request
     * @return
     */
    public Map download(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONObject condition = jo.getJSONObject("condition");
        String specification = condition.getString("specification");
        String brand = condition.getString("brand");
        String pn = condition.getString("pn");
        if("".equals(specification)){
            specification=null;
        }
        if("".equals(brand)){
            brand=null;
        }
        if("".equals(pn)){
            pn=null;
        }

        Page<TyreProduct> page = tyreProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("specification", "EQ", specification,
                "brand", "EQ", brand,
                "pn", "EQ", pn),
                PageRequest.of(request.get("page"), request.get("size"), Sort.by(Sort.Direction.DESC, "id")));
           return MapUtil.mapper("content", page.getContent(), "total", page.getTotalElements(), "pages", page.getTotalPages(), "page", request.get("page"));
    }



    /**
     * 批量删除
     *
     * @param request
     * @return
     */
    public Map delTyreProduct(SimpleRequest request){
        List<TyreProduct> tyreProducts = request.getA("del", TyreProduct.class);
        for (TyreProduct tyreProduct : tyreProducts) {
            tyreProductRepository.delete(tyreProduct);
        }
        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }


    /**
     * 添加
     * @param request
     * @return
     */
    public TyreProduct insertTyreProduct(SimpleRequest request){
        JSONObject jo = request.getJO();
        TyreProduct tyreProduct  = jo.getObject("data",TyreProduct.class);
        return tyreProductRepository.saveAndFlush(tyreProduct);
    }


    /**
     * 根据品牌+规格+花纹+载重指数+速度等级+是否防爆获取单个轮胎标准商品
     * @param request
     * @return
     */
    public List<TyreProduct> getTyreProduct(SimpleRequest request){
        JSONObject param = request.getJO();
        String brand = param.getString("brand");
        String specification = param.getString("specification");
        String figure = param.getString("figure");
        String loadIndex = param.getString("loadIndex");
        String speedClass = param.getString("speedClass");
        Boolean antiExplosion = param.getBoolean("antiExplosion");
        return tyreProductRepository.findByBrand(brand, specification, figure, loadIndex, speedClass, antiExplosion);
    }
}
